﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.Design.WebControls;
using EnvDTE;
using VSLangProj;
using System.Windows.Forms;
using System.Web.UI.Design;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;

namespace Catalyst.Web.DynamicData.Design
{
    public class DynamicFilterContainerBaseDesigner : DataBoundControlDesigner
    {
        private Project _project;
        private IWebApplication _webApplication;

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);
            ProjectItem projectItem = GetService(typeof(ProjectItem)) as ProjectItem;
            _project = projectItem.ContainingProject;
            _webApplication = GetService(typeof(IWebApplication)) as IWebApplication;
            AddAssemblyToConfigFile();
            AddDefaultTempaltesToProject();
            AddReferences();
        }

        private void AddAssemblyToConfigFile()
        {
            WebConfigFile file = new WebConfigFile(_webApplication);
            file.AddAssembly();
        }

        private void AddDefaultTempaltesToProject()
        {
            FilterTemplateCreator creator = FilterTemplateCreator.GetTemplateCreator(_project);
            if (!creator.FiltersExist)
            {
                if (DialogResult.Yes == MessageBox.Show("Would you like to create the default filter tempaltes?", "Create Templates?", MessageBoxButtons.YesNo))
                {
                    creator.CreateDefaultFilters();
                }
            }

        }

        public override DesignerActionListCollection ActionLists
        {
            get
            {
                DesignerActionListCollection collection = base.ActionLists;
                collection.Add(new UpgradeDataSourceDesignerActionList(this.Component, this));
                return collection;
            }
        }

        private void AddReferences()
        {
            VSProject project = _project.Object as VSProject;
            if (project != null)
            {
                AddReference(project, new AssemblyName("Catalyst.ComponentModel.DataAnnotations"));
                AddReference(project, new AssemblyName("Catalyst.Web.DynamicData"));
            }
        }

        private void AddReference(VSProject project, AssemblyName assemblyName)
        {
            References references = project.References; 
            for (int i = references.Count; i > 0; i--)
            {
                if (assemblyName.Equals(string.Equals(references.Item(i).Name, assemblyName.Name, StringComparison.InvariantCultureIgnoreCase)))
                    references.Item(i).Remove();
            }
            references.Add(assemblyName.ToString());
        }

    }
}
